package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> catagoryTreeList() {
        //查询所有
        List<CategoryEntity> list = list();

        //取得根节点
        List<CategoryEntity> collect = list.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .sorted((o1, o2) -> o1.getSort()- o2.getSort())
                .collect(Collectors.toList());
        for (CategoryEntity categoryEntity : collect) {
            getChildrens(categoryEntity,list);
        }

        return collect;
    }
    /**
     * 递归取得子孙
     */
    private void getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> list) {
        List<CategoryEntity> collect = list.stream().filter(categoryEntity1 -> categoryEntity1.getParentCid() == categoryEntity.getCatId())
                .map(s -> {
                    getChildrens(s, list);
                    return s;
                }).sorted((o1, o2) -> o1.getSort()- o2.getSort()).collect(Collectors.toList());
        categoryEntity.setChildrens(collect);
    }

    @Override
    public void updateList(List<CategoryEntity> categoryEntities) {
        updateBatchById(categoryEntities);
    }
}